package com.nsgf.library.ui.page.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.kunminx.architecture.domain.message.MutableResult;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.AccountService;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.DialogNsgfTaskPlanDetailBinding;
import com.nsgf.library.databinding.FragmentTaskPlanListBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.domain.request.BaseHttpObserver;
import com.nsgf.library.domain.request.HttpOnNextListener;
import com.nsgf.library.ui.adapter.TaskPlanListAdapter;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;

/**
 * 任务计划
 */
public class TaskPlanPageFragment extends BaseFragment {
    TaskPlanFragmentStates mStates;

    private TaskPlanListAdapter mAdapter;

    private AccountRequester mAccountRequester;
    LibraryInfo item;

    public static TaskPlanPageFragment newInstance(String type, String planId) {
        TaskPlanPageFragment taskPlanPageFragment = new TaskPlanPageFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("planId", planId);
        taskPlanPageFragment.setArguments(bundle);
        return taskPlanPageFragment;
    }

    private String getType() {
        return getArguments().getString("type");
    }

    public String getPlanId() {
        return getArguments().getString("planId");
    }

    @Override
    protected void initViewModel() {

        mStates = getActivityScopeViewModel(TaskPlanFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    private FragmentTaskPlanListBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new TaskPlanListAdapter(getContext());

        return new DataBindingConfig(R.layout.fragment_task_plan_list, BR.vm, mStates).addBindingParam(BR.adapter, mAdapter).addBindingParam(BR.click, new ClickProxy());
    }

    Dialog dialog = null;
    DialogNsgfTaskPlanDetailBinding binding;

    private MutableResult<ResponseStatus<LibraryInfo>> taskDetailResult = new MutableResult<>();

    public MutableResult<ResponseStatus<LibraryInfo>> getTaskDetailResult() {
        return taskDetailResult;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (FragmentTaskPlanListBinding) getBinding();
        search();
        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            this.item = item;
            mAccountRequester.taskPlanDetail(item.getId(), taskDetailResult);
        });
        getTaskDetailResult().observe(this, libraryInfoResponseStatus -> {

            if (libraryInfoResponseStatus.getResponseCode() == 200) {

                if (null == dialog) {
                    dialog = new Dialog(getActivity(), R.style.dialogstyle);

                    View view12 = View.inflate(getActivity(), R.layout.dialog_nsgf_task_plan_detail, null);
                    binding = DataBindingUtil.bind(view12);
                    binding.ivClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view1) {
                            dialog.dismiss();
                        }
                    });

                    dialog.setContentView(view12);
                }
                if (dialog.isShowing())
                    dialog.dismiss();

                binding.setVm(libraryInfoResponseStatus.getData());
                binding.setItem(item);
                Window window = dialog.getWindow();
                window.setBackgroundDrawableResource(android.R.color.transparent);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = getResources().getDisplayMetrics().widthPixels;
                window.setAttributes(lp);
                window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                dialog.show();
            }else {
                ToastUtils.showLongToast(libraryInfoResponseStatus.getMsg());
            }

        });

        mBinding.recyclerView.setItemAnimator(null);

    }


    private int year;
    private int month;
    private int week;

    Calendar calendar = Calendar.getInstance();

    public void search() {
        search(calendar);
    }

    public void search(Calendar calendar) {
        this.calendar = calendar;
        year = Kits.Date.getYear(calendar.getTimeInMillis());
        month = Kits.Date.getMonth(calendar.getTimeInMillis());
        week = Kits.Date.WeekOfMonth(calendar.getTimeInMillis());

        Observable observable = DataRepository.getRetrofitInstance().create(AccountService.class).taskPlanList("year".equals(getType()) ? "" : String.valueOf(month), "year".equals(getType()) ? "" : String.valueOf(week), getPlanId(), getType(), true);
        BaseHttpObserver observer = new BaseHttpObserver(new HttpOnNextListener<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onSuccess(ResponseStatus<List<LibraryInfo>> dataResult) {
                if (dataResult.getResponseCode() == 200) mAdapter.submitList(dataResult.getData());
                if (dataResult.getData().size() == 0) {
                    mBinding.notdata.setVisibility(View.VISIBLE);
                } else
                    mBinding.notdata.setVisibility(View.GONE);
            }

            @Override
            public void onFail(String e) {
                ToastUtils.showLongToast(e);
            }

            @Override
            public void onComplete() {
            }
        });
        DataRepository.getInstance().subscribe(observable, observer);

    }


    public static class TaskPlanFragmentStates extends StateHolder {

        public final State<String> time = new State<>("");
        public final State<String> timey = new State<>("");

        public final State<List<LibraryInfo>> list = new State<>(new ArrayList<>());

        public final State<Boolean> loadingVisible = new State<>(false);


    }


    private String startTime = "";
    private String endTime = "";
    private String sources = "";

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public class ClickProxy {

        public void autoRefresh() {
            mBinding.smartRefreshLayout.autoRefresh();
        }

    }

}
